/*************************************************************************
    > File Name: more.c
    > Author: Xing.Dai
    > Mail: Xing.Dai@aliyun.com 
    > Created Time: 2017-05-05 18:28
 ************************************************************************/

#include<stdio.h>
#include <stdlib.h>
#define PAGE_LEN	24
#define LINE_LEN	512



/**
 * @Synopsis  Terminal see more infomation
 *
 * @Returns   
 */
int see_more(FILE *cmd)
{
	int c;

	printf("\033[7m more? \033[m");	// reverse on a vt100

	while((c = getc(cmd)) != EOF){	// get response
		switch(c){
			case 'q':	// q -> N
				return 0;
			case ' ':	// ' ' -> next page
				return PAGE_LEN;	// How many to show
			case '\n':	// Entery key -> 1 line.
				return 1;
			default:
				break;
		}
	}

	return 0;
}

/**
 * @Synopsis Read PAGE_LEN lines, then call see_more() for further instructions. 
 *
 * @Param fp
 */
void do_more(FILE *fp)
{
	char line[LINE_LEN];
	int num_of_lines = 0;
	int reply = 0;
	FILE *fp_tty = NULL;

	fp_tty = fopen("/dev/tty", "r");
	if(fp_tty == NULL)
		exit(1);

	while(fgets(line, LINE_LEN, fp)){
		if(num_of_lines == PAGE_LEN){
			reply = see_more(fp_tty);
			if(reply == 0){
				break;
			}
			num_of_lines -= reply;
		}
		if(fputs(line, stdout) == EOF)
			exit(1);	// die
		num_of_lines++;
	}
	
}


int main(int argc, char **argv)
{
	FILE *fp;
	if(argc == 1)
		do_more(stdin);
	else 
		while(--argc){
			if((fp = fopen(*++argv, "r")) != NULL){
				do_more(fp);
				fclose(fp);
			}
			else 
				exit(1);
		}

	return 0;

}
